﻿using System;
using System.IO;
using static System.Net.Mime.MediaTypeNames;
namespace UpdateVersion
{
	class Program
	{
		const string ROOTFILENAME = "IntoTheVoid.sln";
		static void UpdateVersion(ref string line)
		{
			var first = line.IndexOf('"');
			var second = line.LastIndexOf('"');
			var sVersion = line.Substring(first + 1, second - first - 1);
			var arrVersion = sVersion.Split('.');
			if (arrVersion.Length < 4) return;
			var major = Convert.ToInt32(arrVersion[0]);
			var minor = Convert.ToInt32(arrVersion[1]);
			var build = Convert.ToInt32(arrVersion[2]);
			var amendment = Convert.ToInt32(arrVersion[3]);
			if (++amendment > 999) ++build;
			if (build > 99) ++minor;
			if (minor > 9) ++major;
			var sNewVersion = $"{major}.{minor}.{build}.{amendment}";
			SaveVersion(sNewVersion);
			line = line.Replace(sVersion, sNewVersion);
			Console.WriteLine("this is updateversion app");
		}
		static void SaveVersion(String version)
		{
			try
			{
				DirectoryInfo pathInfo = new DirectoryInfo(Environment.CurrentDirectory);
				var path = pathInfo.FullName;

				// 获取解决方案根路径保存version文件
				while (FindTargetFile(path, ROOTFILENAME) == false)
				{
					if (pathInfo.Parent != null)
					{
						pathInfo = new DirectoryInfo(pathInfo.Parent.FullName);
						path = pathInfo.FullName;
					}
				} 

				var rootPath = Path.Combine(path, "version");
				File.WriteAllText(rootPath, version);
			}
			catch (Exception ex) 
			{ 
				Console.WriteLine(ex.Message); 
			}
		}
		static bool FindTargetFile(string path,string fileName)
		{
			bool result = false;
			DirectoryInfo root = new DirectoryInfo(path);
			foreach (FileInfo f in root.GetFiles())
			{
				if(f.Name == fileName)
				{
					result = true;
					break;
				}
			}

			return result;
		}
		static void Main(string[] args)
		{
			if (args.Length != 1 || !File.Exists(args[0])) return;
			var lines = File.ReadAllLines(args[0]);
			for (int i = lines.Length - 1; i >= 0; i--)
			{
				if (lines[i].Contains("assembly: AssemblyFileVersion"))
				{
					UpdateVersion(ref lines[i]);
				}
				if (lines[i].Contains("assembly: AssemblyVersion") && !lines[i].Contains("*"))
				{
					UpdateVersion(ref lines[i]);
					break;
				}
			}
			File.WriteAllLines(args[0], lines);
		}
	}
}